package com.tuanzi.loan.web.bean.extratemplate;

import com.google.common.collect.Lists;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import com.starbaba.model.utils.JSONUtils;
import com.tuanzi.loan.business.entity.extratemplate.ExtraTemplate;
import com.tuanzi.loan.business.entity.extratemplate.ExtraTemplateSpecial;
import com.tuanzi.loan.business.service.extratemplate.ExtraTemplateService;
import com.tuanzi.loan.business.service.extratemplate.ExtraTemplateSpecialService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.view.family.LargeAmountTempDownInfo;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

/**
 * @author caiwanlin
 * @create 2018-10-16 16:31
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class ExtraTemplateInfoBean extends JSFInfoBean<ExtraTemplate> {
    private static final long serialVersionUID = 6501838781301486644L;

    @Autowired
    private ExtraTemplateService extraTemplateService;
    @Autowired
    private ExtraTemplateSpecialService extraTemplateSpecialService;


    private List<ExtraTemplateSpecial> specialList;
    private ExtraTemplateSpecial special = null;

    private List<String> channelIdList;
    private List<LargeAmountTempDownInfo> androidDownList = new ArrayList<>();
    private List<LargeAmountTempDownInfo> iosDownList = new ArrayList<>();
    private Integer androidDown = 0;
    private Integer iosDown = 0;

    @PostConstruct
    private void init() {
        String id = getParamFromRequest("id");
        if (StringUtils.isNotBlank(id)) {
            $ = extraTemplateService.findOne(Long.parseLong(id));
            specialList = extraTemplateSpecialService.findAllByTemplateId($.getTemplateId());
        } else {
            $ = new ExtraTemplate();
            specialList = Lists.newArrayList();
            changeStatusToAdd();
        }
        special = new ExtraTemplateSpecial();
        channelIdList = Lists.newArrayList();
        initDownInfo($);
    }

    private void initDownInfo(ExtraTemplate extraTemplate){
        String androidDownLoadInfo = extraTemplate.getAndroidDownloadInfo();
        if(StringUtils.isNotBlank(androidDownLoadInfo)){
            androidDownList = JSONUtils.fromJsonArrayNew(androidDownLoadInfo, LargeAmountTempDownInfo.class);
            androidDown = 1;
        }

        String iosDownLoadInfo = extraTemplate.getIosDownloadInfo();
        if(StringUtils.isNotBlank(iosDownLoadInfo)){
            iosDownList = JSONUtils.fromJsonArrayNew(iosDownLoadInfo, LargeAmountTempDownInfo.class);
            iosDown =1;
        }

        //补充到3个
        int size = androidDownList.size();
        for (int i=0; i< 3- size; i++){
            androidDownList.add(new LargeAmountTempDownInfo());
        }

        int iosSize = iosDownList.size();
        for (int i=0; i< 3- iosSize; i++){
            iosDownList.add(new LargeAmountTempDownInfo());
        }
    }

    public void onSave() {
        //删除缓存
        extraTemplateService.deleteExtraTemplateCache($.getTemplateId());
        if (!validateImage()) return;
        try {

            List<LargeAmountTempDownInfo> aDownInfoList = androidDownList.stream()
                    .filter(info -> info.getChannelCode() != null && info.getProductId() != null).collect(Collectors.toList());
            if(aDownInfoList != null && aDownInfoList.size() > 0 && this.showAndroidRecommend()){
                $.setAndroidDownloadInfo(JSONUtils.toJsonString(aDownInfoList));
            }else{
                $.setAndroidDownloadInfo(null);
            }

            List<LargeAmountTempDownInfo> iDownInfoList = iosDownList.stream()
                    .filter(info -> info.getChannelCode() != null && info.getProductId() != null).collect(Collectors.toList());
            if(iDownInfoList != null && iDownInfoList.size() > 0 && this.showIosRecommend()){
                $.setIosDownloadInfo(JSONUtils.toJsonString(iDownInfoList));
            }else {
                $.setIosDownloadInfo(null);
            }

            extraTemplateService.onSave($, specialList);
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getCause().getCause() instanceof MySQLIntegrityConstraintViolationException){
                addErrorMessage("该模板ID已经存在了");
                return;
            }
        }
        $ = extraTemplateService.findOne($.getId());
        addSuccessfullyMessage();
        changeStatusToView();
    }

    public boolean showAndroidRecommend(){
        return 1 == androidDown;
    }

    public boolean showIosRecommend(){
        return 1 == iosDown;
    }

    public void onAddSpecial() {
        special = new ExtraTemplateSpecial();
        channelIdList = Lists.newArrayList();
        update("extraTemplateForm:add-dialog");
    }

    public void onSeeSpecial(Integer rowIndex) {
        special = specialList.get(rowIndex);
        channelIdList = Arrays.asList(special.getChannel().split(","));
    }

    public void onDeleteSpecial(Integer rowIndex){
        ExtraTemplateSpecial extraTemplateSpecial = specialList.get(rowIndex);
        Long id = extraTemplateSpecial.getId();
        if (id != null){
            extraTemplateSpecialService.delete(extraTemplateSpecialService.findOne(id));
            //删除缓存
            extraTemplateService.deleteExtraTemplateCache(extraTemplateSpecial.getTemplateId());
        }
        specialList.remove(extraTemplateSpecial);
    }

    public void onSaveSpecial() {
        //验证数据有效性
        boolean flag = validateSpecial();
        if (flag == false) return;
        //添加
        String collect = channelIdList.stream().collect(Collectors.joining(","));
        special.setChannel(collect);
        if (!specialList.contains(special)) {
            specialList.add(special);
        }
        update("extraTemplateForm");

    }

    public void onSpecialSelectPlatform() {
        structureSpecialTemplate($);
    }

    public void onUploadAndroidBanner(FileUploadEvent event) {
        $.setAndroidBanner(this.uploadImg(event.getFile()));
    }

    public void onUploadAndroidRegisterImg(FileUploadEvent event) {
        $.setAndroidRegisterImg(this.uploadImg(event.getFile()));
    }

    public void onUploadAndroidRemarkImg(FileUploadEvent event) {
        $.setAndroidRemarkImg(this.uploadImg(event.getFile()));
    }

    public void onUploadIosBanner(FileUploadEvent event) {
        $.setIosBanner(this.uploadImg(event.getFile()));
    }

    public void onUploadIosRegisterImg(FileUploadEvent event) {
        $.setIosRegisterImg(this.uploadImg(event.getFile()));
    }

    public void onUploadIosRemarkImg(FileUploadEvent event) {
        $.setIosRemarkImg(this.uploadImg(event.getFile()));
    }

    public void onUploadSpecialBanner(FileUploadEvent event) {
        special.setBanner(this.uploadImg(event.getFile()));
    }

    public void onUploadSpecialRegisterImg(FileUploadEvent event) {
        special.setRegisterImg(this.uploadImg(event.getFile()));
    }

    public void onUploadSpecialRemarkImg(FileUploadEvent event) {
        special.setRemarkImg(this.uploadImg(event.getFile()));
    }

    private void structureSpecialTemplate(ExtraTemplate extraTemplate) {
        String platform = special.getPlatform();
        if ("android".equals(platform)) {
            special.setTitle(extraTemplate.getAndroidTitle());
            special.setTheme(extraTemplate.getAndroidTheme());
            special.setBanner(extraTemplate.getAndroidBanner());
            special.setRegisterType(extraTemplate.getAndroidRegisterType());
            special.setQuestion(extraTemplate.getAndroidQuestion());
            special.setBtnText(extraTemplate.getAndroidBtnText());
            special.setBtnBottomText(extraTemplate.getAndroidBtnBottomText());
            special.setRegisterImg(extraTemplate.getAndroidRegisterImg());
            special.setRemarkImg(extraTemplate.getAndroidRemarkImg());
            special.setRemarkText(extraTemplate.getAndroidRemarkText());
        } else if ("ios".equals(platform)) {
            special.setTitle(extraTemplate.getIosTitle());
            special.setTheme(extraTemplate.getIosTheme());
            special.setBanner(extraTemplate.getIosBanner());
            special.setRegisterType(extraTemplate.getIosRegisterType());
            special.setQuestion(extraTemplate.getIosQuestion());
            special.setBtnText(extraTemplate.getIosBtnText());
            special.setBtnBottomText(extraTemplate.getIosBtnBottomText());
            special.setRegisterImg(extraTemplate.getIosRegisterImg());
            special.setRemarkImg(extraTemplate.getIosRemarkImg());
            special.setRemarkText(extraTemplate.getIosRemarkText());
        } else {
            special = new ExtraTemplateSpecial();
            System.out.println("*****空");
        }

    }

    public void deleteImg(String type){
        switch (type){
            case "androidBanner":
                $.setAndroidBanner(null);
                break;
            case "androidRegisterImg":
                $.setAndroidRegisterImg(null);
                break;
            case "androidRemarkImg":
                $.setAndroidRemarkImg(null);
                break;
            case "iosBanner":
                $.setIosBanner(null);
                break;
            case "iosRegisterImg":
                $.setIosRegisterImg(null);
                break;
            case "iosRemarkImg":
                $.setIosRemarkImg(null);
                break;
            case "specialBanner":
                special.setBanner(null);
                break;
            case "specialRegisterImg":
                special.setRegisterImg(null);
                break;
            case "specialRemarkImg":
                special.setRemarkImg(null);
                break;
        }
    }

    private boolean validateSpecial() {
        if (StringUtils.isBlank(special.getPlatform())) {
            addErrorMessage("请选择平台");
            return false;
        }
        if (channelIdList == null || channelIdList.isEmpty()) {
            addErrorMessage("请选择作用渠道");
            return false;
        }
        if (StringUtils.isBlank(special.getTitle())) {
            addErrorMessage("网页标题为空");
            return false;
        }
        if (special.getTheme() == null) {
            addErrorMessage("请选择主题颜色");
            return false;
        }
        if (StringUtils.isBlank(special.getBanner())) {
            addErrorMessage("banner为空");
            return false;
        }
        if (special.getRegisterType() == null) {
            addErrorMessage("请选择登记类型");
            return false;
        }
        if (StringUtils.isBlank(special.getQuestion())) {
            addErrorMessage("请选择登记框下信息");
            return false;
        }
        if (StringUtils.isBlank(special.getBtnText())) {
            addErrorMessage("按钮文案为空");
            return false;
        }
      /*  if (StringUtils.isBlank(special.getRemarkImg())) {
            addErrorMessage("备注图为空");
            return false;
        }
        if (StringUtils.isBlank(special.getRemarkText())) {
            addErrorMessage("备注区文案为空");
            return false;
        }*/
        return true;
    }

    public boolean validateImage() {
        if ($.getTemplateId() == null){
            addErrorMessage("模板ID为空");
            return false;
        }
        if (StringUtils.isBlank($.getAndroidBanner())) {
            addErrorMessage("android页面的banner为空");
            return false;
        }
      /*  if (StringUtils.isBlank($.getAndroidRemarkImg())) {
            addErrorMessage("android页面的备注图为空");
            return false;
        }*/
        if (StringUtils.isBlank($.getIosBanner())) {
            addErrorMessage("ios页面的banner为空");
            return false;
        }
       /* if (StringUtils.isBlank($.getIosRemarkImg())) {
            addErrorMessage("ios页面的备注图为空");
            return false;
        }*/
        return true;
    }

    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(EXTRA_TEMPLATE_PC_SHOW, EXTRA_TEMPLATE_THEME,
                EXTRA_TEMPLATE_REGISTER_TYPE, EXTRA_TEMPLATE_QUESTION, EXTRA_TEMPLATE_AGREEMENT);
    }
}
